/*
 * Copyright © 2019-2020  Whale Cloud, Inc. All Rights Reserved.
 *
 * Notice: Whale Cloud Inc copyrights this specification.
 * No part of this specification may be reproduced in any form or means,
 * without the prior written consent of Whale Cloud Inc.
 *
 */
package com.wteam.modules.system.service.impl;

import com.wteam.modules.system.domain.dto.CusPage;
import com.wteam.modules.system.domain.mapper.CourseMapper;
import com.wteam.modules.system.repository.CourseRepository;
import com.wteam.modules.system.service.SectionService;
import com.wteam.modules.system.domain.Section;
import com.wteam.modules.system.domain.dto.SectionDTO;
import com.wteam.modules.system.domain.criteria.SectionQueryCriteria;
import com.wteam.modules.system.domain.mapper.SectionMapper;
import com.wteam.modules.system.repository.SectionRepository;
import com.wteam.exception.BadRequestException;
import com.wteam.utils.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.cache.annotation.*;
import lombok.RequiredArgsConstructor;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 课程章节 业务实现层.
 *
 * @author herry_wong
 * @since 2020-12-29
 */
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "section")
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class SectionServiceImpl implements SectionService {

    private final SectionRepository sectionRepository;
    private final SectionMapper sectionMapper;

    private final CourseRepository courseRepository;
    private final CourseMapper courseMapper;


    private final RedisUtils redisUtils;

    @Override
    public Map<String,Object> queryAll(SectionQueryCriteria criteria, Pageable pageable){
        Page<Section> page = sectionRepository.findAll((root, criteriaQuery, criteriaBuilder) ->  QueryHelper.andPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SectionDTO> sectionDTOPage = page.map(sectionMapper::toDto);
        Page<SectionDTO> cusPage = new CusPage<>(sectionDTOPage);
        for (SectionDTO sectionDTO: cusPage){
            Collections.replaceAll(cusPage.getContent(),sectionDTO,findDTOById(sectionDTO.getId()));
        }
        return PageUtil.toPage(cusPage);
    }

    @Override
    public List<SectionDTO> queryAll(SectionQueryCriteria criteria){
        return sectionMapper.toDto(sectionRepository.findAll((root, criteriaQuery, criteriaBuilder) ->  QueryHelper.andPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
//    @Cacheable(key = "'id:' + #p0")
    public SectionDTO findDTOById(Long id) {
        Section section = sectionRepository.findById(id).orElse(null);
        ValidUtil.notNull(section, Section.ENTITY_NAME, "id", id);
        SectionDTO sectionDTO = sectionMapper.toDto(section);
        sectionDTO.setCourseDTO(courseMapper.toDto(courseRepository.findById(section.getCourseId()).orElse(null)));
        return sectionDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SectionDTO create(Section resources) {
        return sectionMapper.toDto(sectionRepository.save(resources));
    }

    @Override
    @CacheEvict(key = "'id:' + #p0.id")
    @Transactional(rollbackFor = Exception.class)
    public void update(Section resources) {
        Section section = sectionRepository.findById(resources.getId()).orElse(null);
        ValidUtil.notNull(section, Section.ENTITY_NAME, "id",resources.getId());

        section.copy(resources);
        sectionRepository.save(section);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(Set<Long> ids) {
        redisUtils.delByKeys("section::id:", ids);
        sectionRepository.logicDeleteInBatchById(ids);
    }

    @Override
    public void download(List<SectionDTO> queryAll, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SectionDTO section : queryAll) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("课程id", section.getCourseId());
            map.put("开始时间", section.getStartTime());
            map.put("结束时间", section.getEndTime());
            map.put("创建时间", section.getCreatedAt());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}